<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta
    name="viewport"
    content="initial-scale=1.0, user-scalable=no, width=device-width"
  />
  <title>HELLO，AMAP!</title>
  <style>
    html,
    body,
    #container {
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
    }
    .amap-logo{display: none;opacity:0 !important;}
    .amap-copyright {opacity:0;}
  </style>
</head>

<body>
  <div id="container"></div>
  <script type="text/javascript">
    window._AMapSecurityConfig = {
      securityJsCode: "a2e32fd92179736b559cd4ab416869fe",
    };
  </script>
  <script src="https://webapi.amap.com/loader.js"></script>
  <script src="qrc:///qtwebchannel/qwebchannel.js"></script>
  <script type="text/javascript">
    var markerDict = {};
    var UAVMarkerDict ={};
    var polineDict = {};
    var uavPICs = [//'',
                    //'',
                    '',
                    '',   
                  ];
    var UGVMarkerDict ={};
    // var ugvPICs =['']
    var ugvPICs = ['']
    // 等待 WebChannel 初始化完成
    new QWebChannel(qt.webChannelTransport, function (channel) {
        window.pybridge = channel.objects.pybridge;
        // 加载 AMap API
        AMapLoader.load({
          key: "8204c49dbc4c9070ee8d838070f1c462", //申请好的Web端开发者 Key，调用 load 时必填
          version: "2.0", //指定要加载的 JS API 的版本，缺省时默认为 1.4.15
        })
          .then((AMap) => {
            // 加载完成后，创建地图实例
            window.map = new AMap.Map("container",{
              center:new AMap.LngLat(119.515293,32.199403),
              zoom: 16
            });
            map.plugin(["AMap.MapType"],function(){
            //地图类型切换
              var type= new AMap.MapType({
                defaultType: 0,
              });
              map.addControl(type);
            });

            // 监听地图加载完成事件
            if (window.pybridge) {
              window.pybridge.mapLoaded();
            }
            
            var clickHandler = function(e) {
                //alert('您在[ '+e.lnglat.getLng()+','+e.lnglat.getLat()+' ]的位置点击了地图！');
                if (window.pybridge) {
                    window.pybridge.showCoordinates(e.lnglat.getLat(),e.lnglat.getLng());
                };
            };

            //绑定事件
            map.on('click', clickHandler);

          });
    });

    function deleteMarker(name) {
      if (markerDict[name]) {
          markerDict[name].remove();
          delete markerDict[name];
      }
    };

    function createMarker(latitude, longitude, name) {

      var marker = new AMap.Marker({
        position: new AMap.LngLat(longitude, latitude), //经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
        anchor: 'bottom-center',
      });
      markerDict[name] = marker;
      marker.setMap(map) // 将标记添加到地图上
    };

    function deleteSortedMarkers(prefix) {
      const pattern = new RegExp(`^${prefix}\\*\\d+$`);
      for (const key in markerDict) {
          if (markerDict.hasOwnProperty(key) && pattern.test(key)) {
              markerDict[key].remove();
              delete markerDict[key];
          }
      }
    };

    function deleteAllMarkers() {
      for (var name in markerDict) {
        if (markerDict.hasOwnProperty(name)) {
          markerDict[name].remove(); 
          delete markerDict[name];  
        }
      }
    };
    
    function createUAVMarker(latitude, longitude, id) {
      const markerCount = Object.keys(UAVMarkerDict).length;
      var marker = new AMap.Marker({
        position: new AMap.LngLat(longitude, latitude), //经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        icon: new AMap.Icon({
          size: new AMap.Size(32, 32),         // 统一显示大小
          image: uavPICs[markerCount],         // base64 图片
          imageSize: new AMap.Size(32, 32)     // 强制缩放到 32x32
    }),
        offset: new AMap.Pixel(-16, -16)  ,     // 图标偏移，保证中心对齐
        autoRotation: true,
        rotationOrigin: "center center",
        zIndex: 100
  });
      UAVMarkerDict[id] = marker;
      
      marker.setMap(map) // 将标记添加到地图上        
    }

    function updateUAVMarker(latitude, longitude, yaw, id) {
      if (UAVMarkerDict[id]) {
          UAVMarkerDict[id].setPosition(new AMap.LngLat(longitude, latitude));
          UAVMarkerDict[id].setAngle(yaw);
      }
      if (window.HiddenPlaceMarkers && window.HiddenPlaceMarkers[id]) {
       try {
          window.HiddenPlaceMarkers[id].setPosition(new AMap.LngLat(longitude, latitude));
          window.HiddenPlaceMarkers[id].setAngle(yaw); 
       } catch (e) { console.warn("UAV dot sync failed:", e); }
      }
}

    function createUGVMarker(latitude, longitude, id) {
      const markerCount = Object.keys(UGVMarkerDict).length;
      var marker = new AMap.Marker({
        position: new AMap.LngLat(longitude, latitude), //经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        icon: ugvPICs[markerCount],
        anchor: 'center',
        autoRotation: true,
        rotationOrigin: "center center",
        zIndex: 50
      });
      UGVMarkerDict[id] = marker;
      
      marker.setMap(map) // 将标记添加到地图上     
    }

    function updateUGVMarker(latitude, longitude, yaw, id) {
      if (UGVMarkerDict[id]) {
          UGVMarkerDict[id].setPosition(new AMap.LngLat(longitude, latitude));
          UGVMarkerDict[id].setAngle(yaw);
      }
      if (window.HiddenPlaceMarkers && window.HiddenPlaceMarkers[id]) {
        try {
          window.HiddenPlaceMarkers[id].setPosition(new AMap.LngLat(longitude, latitude));
          window.HiddenPlaceMarkers[id].setAngle(yaw); 
        } catch (e) { console.warn("UGV dot sync failed:", e); }
      }
    }

    function deletePolyline(name) {
      if (polineDict[name]) {
          polineDict[name].remove();
          delete polineDict[name];
      }
    };
    //pahts = [[116.39, 39.9], [116.49, 39.9], [116.49, 39.8]];
    function createPolyline(paths, color, name, weight,opacity) {
      var polyline = new AMap.Polyline({
        path: paths,
        // strokeColor: '#FF33FF', // 线颜色
        strokeColor: color, // 线颜色
        strokeWeight: weight, // 线宽
        strokeOpacity: opacity// 线透明度
      });
      polineDict[name] = polyline;
      polyline.setMap(map) 
    };

    function appendPointtoPolyline(name, point){
      if (polineDict[name]) {
        var polyline = polineDict[name];
        var tempArray = polyline.getPath();
        tempArray.push(point);
        polyline.setPath(tempArray);
      }
    }

    function covertWGStoGCJ(latitude, longitude, name){
      var wgsPoint = [longitude,latitude];
      //参数说明：需要转换的坐标或者坐标组，需要转换的坐标类型，转换成功后的回调函数
      AMap.convertFrom(wgsPoint, "gps", function (status, result) {
        //status：complete 表示查询成功，no_data 为查询无结果，error 代表查询错误
        //查询成功时，result.locations 即为转换后的高德坐标系
        if (status === "complete" && result.info === "ok") {
          var lnglats = result.locations; //转换后的高德坐标 Array.<LngLat>
          //在地图上添加点
          //if (window.pybridge) {
           // window.pybridge.showCoordinates(lnglats[0][1],lnglats[0][0]);
         // };
         createMarker(lnglats[0].lat,lnglats[0].lng,name);
        }
      });
    }
    
    var HiddenPlaceMarkers = {};  // 存储隐藏后的占位点

    function hideAllMarkersWithDots() {
        // 清除旧点
        for (var name in HiddenPlaceMarkers) {
            if (HiddenPlaceMarkers.hasOwnProperty(name)) {
                HiddenPlaceMarkers[name].remove();
            }
        }
        HiddenPlaceMarkers = {};

        //QGC三角形参数
        function smallQGCSVG(color) {
            return `
                <svg xmlns="http://www.w3.org/2000/svg" width="8" height="8" viewBox="-8 -8 16 16">
                    <polygon points="0,-7 4,5 0,3 -4,5"
                        fill="${color}" stroke="black" stroke-width="1"/>
                </svg>
            `;
        }

        // UAV 处理，蓝 / 红
        for (var id in UAVMarkerDict) {
            if (UAVMarkerDict.hasOwnProperty(id)) {

                var pos = UAVMarkerDict[id].getPosition();
                UAVMarkerDict[id].setMap(null);

                var color = (id === "uav1") ? "#2196F3" : "#E53935"; // 蓝或红

                var triangle = new AMap.Marker({
                    position: pos,
                    icon: new AMap.Icon({
                        size: new AMap.Size(8, 8),
                        image: 'data:image/svg+xml;base64,' + btoa(smallQGCSVG(color)),
                        imageSize: new AMap.Size(8, 8)
                    }),
                    offset: new AMap.Pixel(-4, -4),
                    autoRotation: true,
                    rotationOrigin: "center center",
                    zIndex: 10
                });

                triangle.setMap(map);
                HiddenPlaceMarkers[id] = triangle;
            }
        }

        // UGV 处理，黄色
        for (var id in UGVMarkerDict) {
            if (UGVMarkerDict.hasOwnProperty(id)) {

                var pos = UGVMarkerDict[id].getPosition();
                UGVMarkerDict[id].setMap(null);

                var color = "#FFC107"; // 黄

                var triangle = new AMap.Marker({
                    position: pos,
                    icon: new AMap.Icon({
                        size: new AMap.Size(8, 8),
                        image: 'data:image/svg+xml;base64,' + btoa(smallQGCSVG(color)),
                        imageSize: new AMap.Size(8, 8)
                    }),
                    offset: new AMap.Pixel(-4, -4),
                    autoRotation: true,
                    rotationOrigin: "center center",
                    zIndex: 10
                });

                triangle.setMap(map);
                HiddenPlaceMarkers[id] = triangle;
            }
        }
    }


    function showAllMarkersWithDots() {
        for (var name in HiddenPlaceMarkers) {
            if (HiddenPlaceMarkers.hasOwnProperty(name)) {
                HiddenPlaceMarkers[name].remove();
            }
        }
        HiddenPlaceMarkers = {};

        for (var id in UAVMarkerDict) {
            UAVMarkerDict[id].setMap(map);
        }
        for (var id in UGVMarkerDict) {
            UGVMarkerDict[id].setMap(map);
        }
    }



  </script>  
</body>

</html>